import { useState, useRef } from "react";
import { useQueryClient, useMutation } from 'react-query';
import { faEdit, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { formatDateTime } from "@/tools/data-helpers";
import { updateExerciseNameById, createExerciseByCourseId } from "@/apis/exercise";


/**
 * This component use react-Query mutaion.
 * More details see: https://react-query.tanstack.com/guides/invalidations-from-mutations
 */
function ExerciseItem({ exercise, courseId, isCourseManager }) {
    const queryClient = useQueryClient();

    const mutateExercise = useMutation(updateExerciseNameById, {
        onSuccess: () => {
            queryClient.invalidateQueries('exercises');
        },
    });
    const createExercise = useMutation(createExerciseByCourseId, {
        onSuccess: () => {
            queryClient.invalidateQueries('exercises');
        },
    });

    const [isEditable, setIsEditable] = useState(false);
    const [isCreating, setIsCreating] = useState(false);

    const changeRef = useRef(null);
    const createRef = useRef(null);

    function handleEdit(e) {
        e.preventDefault();
        setIsEditable(true);
    }

    function handleChange(e) {
        e.preventDefault();
        setIsEditable(false);
        const newExerciseName = changeRef.current.value;
        if (newExerciseName !== exercise.name) {
            mutateExercise.mutate({
                newExerciseName,
                exerciseId: exercise.id,
                courseId,
            });
        }
    }

    function handleCreate(e) {
        e.preventDefault();
        setIsCreating(true);
    }

    function handleSave(e) {
        e.preventDefault();
        setIsCreating(false);
        const exerciseName = createRef.current.value;

        createExercise.mutate({
            exerciseName,
            courseId,
            previousId: exercise.id
        });
    }

    return (
        <li className="my-4" key={exercise && exercise.id}>
            {!isEditable &&
                <div className="row align-items-center">
                    <a className="col-md-3 ms-2 fw-bold" href={`/course/${courseId}/exercise/${exercise.id}`}>{exercise && exercise.name}</a>
                    <small className="col-md-3">{exercise && formatDateTime(exercise.updated_time)}</small>
                    <div className="col-md-1">
                        {(isCourseManager && !isCreating) &&
                            <div className="row">
                                <button className="col  btn btn-outline-secondary btn-sm p-0 mx-1" onClick={handleEdit}><FontAwesomeIcon icon={faEdit} /></button>
                                <button className="col btn btn-outline-secondary btn-sm p-0" onClick={handleCreate}><FontAwesomeIcon icon={faPlus} /></button>
                            </div>
                        }
                    </div>
                </div>
            }
            {isEditable &&
                <div className="row align-items-center">
                    <div className="col-md-9">
                        <div className="input-group ms-2">
                            <input className="form-control" ref={changeRef} type="text" placeholder={exercise && exercise.name} />
                        </div>
                    </div>
                    <div className="col-md-1">
                        <div className="row">
                            <button className="col  btn btn-outline-secondary btn-sm" onClick={handleChange}>保存</button>
                        </div>
                    </div>
                </div>
            }
            {isCreating &&
                <div className="row align-items-center">
                    <div className="col-md-9">
                        <div className="input-group ms-2">
                            <input className="form-control" ref={createRef} type="text" placeholder={exercise && exercise.name} />
                        </div>
                    </div>
                    <div className="col-md-1">
                        <div className="row">
                            <button type="button" className="btn btn-outline-secondary btn-sm" onClick={handleSave}>新建</button>
                        </div>
                    </div>
                </div>
            }
        </li>
    )
}

function ExerciseCreator({ courseId }) {
    const queryClient = useQueryClient();
    const createRef = useRef(null);
    const createExercise = useMutation(createExerciseByCourseId, {
        onSuccess: () => {
            queryClient.invalidateQueries('exercises');
        },
    });
    function handleSave(e) {
        e.preventDefault();
        const exerciseName = createRef.current.value;

        createExercise.mutate({
            exerciseName,
            courseId,
        });
    }
    return (
        <div className="row align-items-center">
            <div className="col-md-9">
                <div className="input-group ms-2">
                    <input className="form-control" ref={createRef} type="text" placeholder="还没有练习册，新建一个" />
                </div>
            </div>
            <div className="col-md-1">
                <div className="row">
                    <button type="button" className="btn btn-outline-secondary btn-sm" onClick={handleSave}>新建</button>
                </div>
            </div>
        </div>
    )
}

export default function CourseExerciseList({ courseId, exercises, isCourseManager }) {
    const exerciseArray = exercises || [];

    const exerciseItems = exerciseArray.map((exercise) => (
        <ExerciseItem key={exercise && exercise.id} courseId={courseId} exercise={exercise} isCourseManager={isCourseManager} />
    ));

    return (
        <ol className="col-md-10">
            {exerciseArray.length === 0 &&
                <ExerciseCreator courseId={courseId} />
            }
            {exerciseItems}
        </ol>
    );
};
